package cn.demomaster.quickui.util;

import static cn.demomaster.quickui.view.floator.DebugFloating2.getTagColor;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;

import com.demomaster.quickcompat.util.DisplayUtil;
import com.demomaster.quickcompat.util.QuickThread;

import java.util.ArrayList;
import java.util.List;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quicklogger.interceptor.LogInterceptor;
import cn.demomaster.quicklogger.model.LogInfo;
import cn.demomaster.quickrouter.quickview.QuickView;
import cn.demomaster.quickrouter.quickview.QuickViewManager;
import cn.demomaster.quickui.R;
import cn.demomaster.quickui.ui.file.FileExplorerActivity;
import cn.demomaster.quickui.view.floatview.RichTextView;

/**
 * app内悬浮工具
 */
public class QuickDevKit {
    public static String TAG = QuickDevKit.class.getSimpleName();
    public void init(Activity context){
        QuickView quickView2 = new QuickView();
        quickView2.setResId(R.layout.quick_layout_floating_kit);
        quickView2.setTag("QuickDevKit");
        quickView2.setX(0);
        quickView2.setzIndex(1000);
        quickView2.setY(DisplayUtil.getScreenHeight(context)/2);//DisplayUtil.dip2px(mContext,50);
        FrameLayout.LayoutParams marginLayoutParams2 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        //marginLayoutParams2.topMargin = DisplayUtil.dip2px(context,5);
        //marginLayoutParams2.rightMargin = DisplayUtil.dip2px(context,5);
        //marginLayoutParams2.gravity=Gravity.RIGHT|Gravity.BOTTOM;
        //marginLayoutParams2.gravity = Gravity.BOTTOM;
        quickView2.setLayoutParams(marginLayoutParams2);
        quickView2.setOnViewLoad(new QuickView.OnViewLoad() {
            @Override
            public void onInflatView(ViewGroup viewGroup, View view) {
                view.post(new Runnable() {
                    @Override
                    public void run() {
                        int top = viewGroup.getMeasuredHeight()/2- view.getMeasuredHeight();
                        //quickView2.setTop(top);
                        int left = viewGroup.getMeasuredWidth()- view.getMeasuredWidth();
                        quickView2.setLeftMargin(left);
                        quickView2.setTopMargin(top);
                        //quickView2.setLayoutParams(layoutParams);
                        QuickViewManager.getInstance().updataViewLayout(context, quickView2);
                    }
                });
                View view1 = view.findViewById(R.id.btn_kit_ruler);
                view1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Activity activity = (Activity) v.getContext();
                        if(QuickViewManager.getInstance().findViewByTag("RULER")==null) {
                            //Toast.makeText(activity,"add RULER",Toast.LENGTH_LONG).show();
                            addRuler(activity);
                        }else {
                            //Toast.makeText(activity,"remove RULER",Toast.LENGTH_LONG).show();
                            QuickViewManager.getInstance().removeViewByTag(activity,"RULER");
                        }
                    }
                });
                View view2 = view.findViewById(R.id.btn_kit_view);
                view2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Activity activity = (Activity) v.getContext();
                        if(QuickViewManager.getInstance().findViewByTag("KONGJIAN")==null) {
                            //Toast.makeText(activity,"add KONGJIAN",Toast.LENGTH_LONG).show();
                            addKongJian(activity);
                        }else {
                            //Toast.makeText(activity,"remove KONGJIAN",Toast.LENGTH_LONG).show();
                            QuickViewManager.getInstance().removeViewByTag(activity,"KONGJIAN");
                        }
                    }
                });
                View btn_kit_console = view.findViewById(R.id.btn_kit_console);
                btn_kit_console.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Activity activity = (Activity) v.getContext();
                        if(QuickViewManager.getInstance().findViewByTag("console")==null) {
                            //Toast.makeText(activity,"add KONGJIAN",Toast.LENGTH_LONG).show();
                            addConsole(activity);
                        }else {
                            //Toast.makeText(activity,"remove KONGJIAN",Toast.LENGTH_LONG).show();
                            QdLog.removeInterceptor(qdLogInterceptor);
                            QuickViewManager.getInstance().removeViewByTag(activity,"console");
                        }
                    }
                });
                View btn_kit_cache = view.findViewById(R.id.btn_kit_cache);
                btn_kit_cache.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(v.getContext().getFilesDir().getParentFile().getAbsolutePath());
                        paths.add(v.getContext().getExternalCacheDir().getAbsolutePath());
                        Intent intent = new Intent(v.getContext(), FileExplorerActivity.class);
                        Bundle bundle = new Bundle();
                        //bundle.putString("DIR_PATH_KEY", mContext.getExternalFilesDir("").getParentFile().getAbsolutePath());
                        bundle.putStringArrayList("DIR_PATHS_KEY", paths);
                        bundle.putBoolean("finishWithActivity", true);
                        intent.putExtras(bundle);
                        v.getContext().startActivity(intent);
                    }
                });
            }
        });
        QuickViewManager.getInstance().addViewInfo(context, quickView2);
        Log.d(TAG,"QuickDevKit init");
    }

    public void addConsole(Activity context){
        if(QuickViewManager.getInstance().findViewByTag("console")==null) {
            QuickView quickView = new QuickView();
            quickView.setResId(R.layout.layout_debug_console);
            quickView.setTag("console");
            quickView.setX(0);
            quickView.setY(0);
            FrameLayout.LayoutParams marginLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            //marginLayoutParams.topMargin = DisplayUtil.getScreenHeight(mContext)/2;
            quickView.setLayoutParams(marginLayoutParams);
            quickView.setOnViewLoad(new QuickView.OnViewLoad() {
                @Override
                public void onInflatView(ViewGroup viewGroup, View view) {
                    initLog(viewGroup);
                }
            });
            QuickViewManager.getInstance().addViewInfo(context, quickView);
        }
    }

    static int strMaxLen = 20000;
    static List<LogInfo> logList = new ArrayList<>();
    static String logStr = "";
    static LogInterceptor qdLogInterceptor;
    private static void initLog(ViewGroup viewGroup) {
        RichTextView tv_log = viewGroup.findViewById(R.id.tv_log);
        tv_log.setText(logStr);
        NestedScrollView scrollView = viewGroup.findViewById(R.id.scrollView);
        scrollView.post(() -> {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
        });
        View tv_close = viewGroup.findViewById(R.id.tv_close);
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QdLog.removeInterceptor(qdLogInterceptor);
                Activity activity = (Activity) v.getContext();
                QuickViewManager.getInstance().removeViewByTag(activity,"console");
            }
        });

        qdLogInterceptor = msg -> QuickThread.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (tv_log.getText().length() > strMaxLen) {
                    logList.clear();
                    tv_log.setText("");
                }
                logList.add(msg);
                int lineNum = tv_log.getLineCount();
                String str = lineNum + " " + msg.getTag() + " " + msg.getMsg() + " \n";

                SpannableStringBuilder builder = new SpannableStringBuilder(str);
                //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(tv_log.getResources().getColor(com.demomaster.quickcompat.R.color.orange));
                //AbsoluteSizeSpan smallSpan = new AbsoluteSizeSpan(12, true);
                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                builder.setSpan(foregroundColorSpan, 0, (lineNum + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//包含两端start和end所在的端点
                ForegroundColorSpan tagColorSpan = new ForegroundColorSpan(Color.WHITE);
                if (msg.getLevel() != null) {
                    tagColorSpan = new ForegroundColorSpan(getTagColor(msg.getLevel().value()));
                }
                builder.setSpan(tagColorSpan, (lineNum + "").length() + 1, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//包含两端start和end所在的端点
                //Spannable.SPAN_EXCLUSIVE_INCLUSIVE);//不包含端start，但包含end所在的端点
                tv_log.append(builder);
                logStr = tv_log.getText().toString();
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
            }
        });
        QdLog.addInterceptor(qdLogInterceptor);
    }


    public void addRuler(Activity context){
        if(QuickViewManager.getInstance().findViewByTag("RULER")==null) {
            QuickView quickView = new QuickView();
            quickView.setResId(R.layout.quick_layout_floating_ruler);
            quickView.setTag("RULER");
            quickView.setX(0);
            quickView.setY(0);
            FrameLayout.LayoutParams marginLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            //marginLayoutParams.topMargin = DisplayUtil.getScreenHeight(mContext)/2;
            marginLayoutParams.leftMargin = 0;
            quickView.setLayoutParams(marginLayoutParams);
            QuickViewManager.getInstance().addViewInfo(context, quickView);
        }
    }

    public void addKongJian(Activity context){
        if(QuickViewManager.getInstance().findViewByTag("KONGJIAN")==null) {
            QuickView quickView = new QuickView();
            quickView.setResId(R.layout.quick_layout_floating_kongjian);
            quickView.setTag("KONGJIAN");
            quickView.setX(0);
            quickView.setY(0);
            FrameLayout.LayoutParams marginLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            //marginLayoutParams.topMargin = DisplayUtil.getScreenHeight(mContext)/2;
            marginLayoutParams.leftMargin = 0;
            quickView.setLayoutParams(marginLayoutParams);
            quickView.setOnViewLoad(new QuickView.OnViewLoad() {
                @Override
                public void onInflatView(ViewGroup viewGroup, View view) {
//                    HierarchyView hierarchyView = view.findViewById(R.id.hierarchyView);
//                    FrameLayout mDecorView = (FrameLayout) ((Activity)view.getContext()).getWindow().getDecorView();
//                    //hierarchyView.setNodeView(mDecorView);//.findViewById(android.R.id.content)
//                    //hierarchyView.setAccessibilityNodeInfo();
//
//                    final View viewInfoLayout = view.findViewById(R.id.viewInfoLayout);
//                    hierarchyView.setOnNodeInfoClickListener(new HierarchyView.OnNodeInfoClickListener() {
//                                                                 @Override
//                                                                 public void onClick(AccessibilityNodeInfo nodeInfo) {
//                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//                                    showNodeInfo(viewInfoLayout, nodeInfo);
//                                }
//                            }});
                }
            });
            QuickViewManager.getInstance().addViewInfo(context, quickView);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void showNodeInfo(View layoutView , AccessibilityNodeInfo nodeInfo1) {
        //QuickAccessNode nodeInfo = new QuickAccessNode(nodeInfo1);
        Rect rect = new Rect();
        //nodeInfo.getAccessibilityNodeInfo().getBoundsInScreen(rect);
        layoutView.setVisibility(View.VISIBLE);
        TextView tv_current_position = layoutView.findViewById(R.id.tv_current_position);
        TextView tv_view_id = layoutView.findViewById(R.id.tv_view_id);
        TextView tv_view_type = layoutView.findViewById(R.id.tv_view_type);
        TextView tv_view_text = layoutView.findViewById(R.id.tv_view_text);
        TextView tv_view_textcolor = layoutView.findViewById(R.id.tv_view_textcolor);
        TextView tv_view_text_size = layoutView.findViewById(R.id.tv_view_text_size);
        TextView tv_view_size = layoutView.findViewById(R.id.tv_view_size);
        TextView tv_activity_name = layoutView.findViewById(R.id.tv_activity_name);
        ImageView iv_colse = layoutView.findViewById(R.id.iv_colse);
        iv_colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutView.setVisibility(View.GONE);
            }
        });

        tv_current_position.setText("(左:"+((int)rect.left)+",上:"+((int)rect.top)+",右:"+((int)rect.right)+",下:"+((int)rect.bottom)+")");
//        tv_view_type.setText(nodeInfo.get().getName());
//        if(targetView instanceof TextView){
//            TextView textView = (TextView) targetView;
//            tv_view_text.setText(textView.getText()+"");
//            tv_view_textcolor.setText(textView.getCurrentTextColor()+"");
//            tv_view_text_size.setText(DisplayUtil.px2sp(targetView.getContext(),textView.getTextSize())+"sp");
//        }else {
//            tv_view_text.setText("");
//            tv_view_textcolor.setText("");
//            tv_view_text_size.setText("");
//        }
//        QdLog.println("view instanceof ="+(targetView instanceof TextView));
//        tv_view_size.setText(targetView.getMeasuredWidth()+"x"+targetView.getMeasuredHeight());
//        tv_activity_name.setText(targetView.getContext().getClass().getName()+"");
//        String idStr = getResourceNameById(targetView.getContext(),targetView.getId());
 //       tv_view_id.setText(idStr+"");
    }

    public void dismiss() {
        QuickViewManager.getInstance().dismiss();//context,"RULER");
    }
    public Boolean isShow() {
        return QuickViewManager.getInstance().isShow();//context,"RULER");
    }
    public void show() {
        QuickViewManager.getInstance().show();
    }
}
